import json
from concurrent.futures import ThreadPoolExecutor

from flask import Flask, render_template

import rec

count = 0

executor = ThreadPoolExecutor(max_workers=1)

app = Flask(__name__)
app.json.ensure_ascii = False


@app.route('/')
def listern():
    global count
    if count == 0:
        rec.recognition.start()
        executor.submit(rec.read)
        count = 1
    return render_template('listern.html')


@app.route('/text', methods=['GET'])
def text():
    with open('myfile.txt', 'r', encoding='utf-8') as file:
        lines = file.readlines()
        if len(lines) > 0:
            last_line = lines[-1]
        else:
            last_line = ''
    if len(last_line) > 0:
        part = last_line.split(' => ')
        return {'timestamp': part[0], 'result': json.loads(part[1])}
    else:
        return {'timestamp': '', 'result': {}}


if __name__ == '__main__':
    app.run(host='0.0.0.0', port='5000')
